package com.woniuxy.provider.listener;

import com.woniuxy.provider.model.entity.Stu;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class EsDeleteListener {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    // 监听删除队列中的消息
    @RabbitListener(queues = "student.delete.es.queue")
    public void deleteFromEs(int id) {
        try {
            Query query = new NativeSearchQueryBuilder()
                    .withQuery(QueryBuilders.termQuery("sno", id)) // 通过 id 字段查询
                    .build();

            // 执行删除操作，删除指定 ID 的文档
            elasticsearchRestTemplate.delete(query, Stu.class, IndexCoordinates.of("stu"));

            log.info("从 Elasticsearch 中删除学生数据，ID: " + id);
        } catch (Exception e) {
            log.error("删除 Elasticsearch 中的数据时出错", e);
        }
    }
}
